
new Vue({
    el:'#app',
    data:{
        //购物车中的数据
        shopListArr:[],
        //是否全选
        isSelectedAll:false,
        //所有商品总价格
        totalPrice:0,
        //是否隐藏删除面板
        isHideDelPanel:true,
        //当前要删除的一个商品
        currentDelShop:{}
    },
    //组件已经加载完毕，请求网络数据
    mounted(){
    //请求本地数据
        this.getLocalData();
    },

    filters:{
        //格式化价格
        moneyFormat(money){
            return '¥' + money.toFixed(2);
        }
    },

    methods:{
        //请求本地数据
        getLocalData(){
        this.$http.get('../data/cart.json').then(response => {
            const res = response.body;
            if (res) {
                this.shopListArr = res.allShops.shopList;
                console.log(this.shopListArr)
            }
          }, response => {
           alert("请求数据失败")
          });
        },

        //单个商品数量加减,shop-这条商品,flag表示加减
        singerShopPrice(shop,flag){
            if (flag) {     //true为加,false为减
                shop.shopNumber += 1;
            }else{
                if (shop.shopNumber <= 1) {
                    shop.shopNumber = 1;
                    return;
                }
                 shop.shopNumber -= 1;  //减
            }
            //计算总价
             this.getAllShopPrice();

        },

        //选中所有商品
        selectAll(flag){
            //全选按钮控制
       this.isSelectedAll = !flag;
       //遍历所有商品数据
        this.shopListArr.forEach((value,index)=>{
            if (typeof value.checked === 'undefined') {
                this.$set(value,'checked',!flag);
            }else{
                value.checked = !flag;
            }
        });
        this.getAllShopPrice();

    },

    //计算商品总价
    getAllShopPrice(){
        let totalPrice = 0;
        //遍历所有的商品
        this.shopListArr.forEach((value,index)=>{
            //判断商品是否被选中
            if (value.checked) {
                totalPrice += value.shopPrice * value.shopNumber;
            }
          
        });
          this.totalPrice = totalPrice;
    },

    //单个商品的选中和取消
    singerShopSelected(shop){
        //判断有没有这个属性
        if (typeof shop.checked === 'undefined') {
             this.$set(shop,'checked',true);
        }else{
            shop.checked = !shop.checked;
        }
        this.getAllShopPrice();
      //判断是否为全选
        this.hasAllSelected();
    },

    //判断是否符合全选
    hasAllSelected(){
        let flag = true;
         this.shopListArr.forEach((value,index)=>{
            if (!value.checked) {
                flag = false;
            }
         });
        this.isSelectedAll = flag;
    },

    //点击垃圾篓
    clickTrash(shop){
        this.isHideDelPanel = false;
        this.currentDelShop = shop;

    },

    //删除当前商品
    delShop(){
        //隐藏panel面板
        this.isHideDelPanel = true;
        const index = this.shopListArr.indexOf(this.currentDelShop);
        this.shopListArr.splice(index,1);
        this.getAllShopPrice();
    }

}
});